<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Model\Admin\Admin;
use App\Model\Admin\Roles;
use App\Model\Distributors;
use App\Model\Normal;
use App\Services\SmsService;
use App\Services\Wechat;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use Phper666\JWTAuth\JWT;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use Util\Common;


class AdminController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;
    protected JWT $jwt;
    protected Wechat $wechat;
    protected SmsService $smsService;

    #[Inject]
    protected Admin $admin;

    #[Inject]
    protected Distributors $distributors;
    #[Inject]
    protected Roles $roles;

    public function __construct()
    {
        $this->jwt = container()->get(JWT::class);
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
        $this->wechat = container()->get(Wechat::class);
        $this->smsService = container()->get(SmsService::class);
    }

    /**
     * 后台登录 with jwt
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws RedisException|InvalidArgumentException
     */
    public function login(RequestInterface $request): ResponseInterface
    {
        $credentials = $request->inputs(['username', 'password']);
        // 验证手机号码格式
//        if (!$this->normal->validateEmail($credentials['username'])) {
//            return $this->error(ErrorCode::EMAIL_ERR);
//        }
        $info = $this->distributors->where('phone','=' ,$credentials['username'])
//            ->where('is_del', '=',Common::DEL_SHOW)
            ->first();
        if (empty($info)) {
            return $this->error(ErrorCode::UNKNOW_EMAIL);
        }
        if(!$info->is_active){
            return $this->error(ErrorCode::PASS_ERR);
        }
        if(!password_verify($credentials['password'],$info->password)){
            return $this->error(ErrorCode::PASS_ERR);
        }
        $info = $this->distributors->makeInfo($info);
        $token = $this->jwt->getToken('admin', $info);
        $stringToken = $token->toString();
        $this->jwt->getTTL($stringToken);
        $this->redis->setex(Common::USER_REDIS_INFO . $info['id'], $this->jwt->getTTL($stringToken) + 30, json_encode($info));
        return $this->success(['token' => $stringToken]);
    }

    /**
     * 检测登录状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function getInfo(RequestInterface $request): ResponseInterface
    {
        $data = $this->distributors->getInfo($request);
        if ($data) {
            return $this->success($data);
        }
        return $this->error(ErrorCode::UNKNOW_INFO);
    }

    /**退出登录
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws InvalidArgumentException
     * @throws NotFoundExceptionInterface
     */
    public function logout(RequestInterface $request): ResponseInterface
    {
        $token = $request->getHeaderLine('Token');
        $this->jwt->logout($token);
        return $this->success(msg: '退出成功');
    }


    /**管理员列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function adminList(RequestInterface $request):ResponseInterface
    {
        try {
            $page = $request->inputs(['page', 'limit', 'keyword']);
            $data['list']= $this->admin->where(function ($query) use ($page) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('name', 'like', '%' . $page['keyword'] . '%');
                    $query->orWhere('email', 'like', '%' . $page['keyword'] . '%');
                }
                $query->where('is_del', Common::DEL_SHOW);
            })->orderBy('id', 'desc')
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit'])
                ->get(['id','name','email','created_at','avatar','roles','type','roles_id','updated_at','show_drawer','show_income'])->toArray();
            foreach($data['list'] as $k => $v){
                if($v['roles_id']>0){
                    $data['list'][$k]['roles_name'] = $this->roles->where('id',$v['roles_id'])->value('name');
                }else{
                    $data['list'][$k]['roles_name'] = '超级管理员';
                }
            }
            $data['total'] = $this->admin->where(function ($query) use ($page) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('name', 'like', '%' . $page['keyword'] . '%');
                    $query->orWhere('email', 'like', '%' . $page['keyword'] . '%');
                }
                $query->where('is_del', Common::DEL_SHOW);
            })->count();
            return $this->success($data);
        } catch (\Exception $e) {
            return $this->error();
        }
    }


    /**创建编辑管理员
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):ResponseInterface
    {
        $data = $request->post();
        if(!$data['email']){
            return $this->error(1001,'请填写邮箱');
        }
        if(!$data['name']){
            return $this->error(1001,'请填写姓名');
        }
        if($data['roles_id'] > 0){
             $data['type'] = 2;
        }
        if (array_key_exists('id',$data) && $data['id'] > 0) {
            $id = $data['id'];
            unset($data['roles_name']);
            if(array_key_exists('updated_at', $data)){
                unset($data['updated_at']);
            }
            if(array_key_exists('password',$data)){
                if($data['password'] ==''){
                    unset($data['password']);
                }else{
                    if (strlen($data['password'])>30 || strlen($data['password'])<6)
                    {
                      $this->error(1001, '密码必须为6-30位的字符串');
                    }
                    $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                }
            }
            unset($data['id']);
            $this->admin->where('id', $id)->update($data);
        } else {
            $check = $this->admin->where('email',$data['email'])->where('is_del',Common::DEL_SHOW)->count();
            if($check>0){
                return $this->error(1002,'邮箱已被注册');
            }
            if (strlen($data['password'])>30 || strlen($data['password'])<6)
            {
               $this->error(1002, '密码必须为6-30位的字符串');
            }
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            Admin::create($data);
        }
        return $this->success();
    }


    /**删除管理员
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request):ResponseInterface
    {
        $id = $request->input('id',0,'int');
        if (!$id) {
            return $this->error(1003,'缺少参数id');
        }
        $this->admin->where('id',$id)->update(['is_del'=>Common::DEL_HIDE]);
        return $this->success(msg:'删除成功');
    }
}
